<template>
	<view class="content">
		<!-- <image class="logo" src="/static/logo.png"></image> -->
		<view>
			<text class="title">{{title}}</text>
		</view>
		
		<!-- 对话记录区域 -->
		<scroll-view class="chat-container" scroll-y :scroll-into-view="'msg-' + (messages.length-1)">
			<view v-for="(item, index) in messages" :key="index" :id="'msg-'+index" 
					class="message" :class="item.type">
				<text>{{item.content}}</text>
				<!-- 显示知识库引用 -->
				<view v-if="item.knowledge" class="knowledge-source">
					<text class="source-text">来源: {{item.knowledge}}</text>
				</view>
			</view>
		</scroll-view>
		
		<!-- 语音波纹动效 -->
		<view class="wave-container" v-show="isRecording">
			<view class="wave-wrapper">
				<view class="wave-item" v-for="i in 4" :key="i"></view>
			</view>
			<text class="wave-text">正在聆听...</text>
		</view>
		
		<!-- 语音按钮区域 -->
		<view class="voice-btn-container">
			<button class="voice-btn" 
					@touchstart="startRecord" 
					@touchend="stopRecord"
					:class="{'recording': isRecording}">
				{{ isRecording ? '松开结束' : '按住说话' }}
			</button>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				title: '您可以提出关于社会工作方面的问题',
				messages: [],
				recorderManager: null,
				isRecording: false,
				botConfig: {
					appKey: 'raDVCEaL',
					baseUrl: 'https://wss.lke.cloud.tencent.com/v1/qbot/chat/sse',
					visitorId: 'visitor_' + Math.random().toString(36).substr(2, 9)
				}
			}
		},
		// 在created生命周期初始化
		created() {
			// #ifdef APP-PLUS || MP
			this.initRecorder();
			// #endif
			
			// 初始化语音识别
			// #ifdef H5
			if ('webkitSpeechRecognition' in window) {
				this.recognition = new webkitSpeechRecognition();
				this.initSpeechRecognition();
			} else if ('SpeechRecognition' in window) {
				this.recognition = new SpeechRecognition();
				this.initSpeechRecognition();
			} else {
				console.warn('当前浏览器不支持语音识别');
			}
			// #endif
		},
		onLoad() {
			// #ifdef H5
			this.initRecorder();
			// #endif
			
			// 测试API连接
			this.testConnection();
		},
		methods: {
			async sendToKnowledgeBot(text) {
				try {
					// 显示用户消息
					this.messages.push({
						type: 'user',
						content: text
					});

					// 添加一个空的AI消息占位
					const aiMessage = {
						type: 'ai',
						content: '',
						knowledge: null
					};
					this.messages.push(aiMessage);

					// 使用 POST 请求
					uni.request({
						url: this.botConfig.baseUrl,
						method: 'POST',
						header: {
							'content-type': 'application/json',
							'Accept': 'text/event-stream'
						},
						data: {
							request_id: Date.now().toString(),
							content: text,
							bot_app_key: this.botConfig.appKey,
							visitor_biz_id: this.botConfig.visitorId,
							session_id: Date.now().toString(),
							streaming_throttle: 1
						},
						success: (res) => {
							console.log('完整响应：', res);
							if (res.statusCode === 200) {
								try {
									// 处理返回的数据
									const lines = res.data.split('\n');
									let lastValidData = null;

									for (const line of lines) {
										if (line.startsWith('data:')) {
											const jsonStr = line.slice(5).trim();
											if (jsonStr) {
												try {
													const data = JSON.parse(jsonStr);
													console.log('解析的数据：', data);
													lastValidData = data;

													if (data.type === 'error') {
														throw new Error(data.error.message);
													}

													if (data.type === 'reply' && data.payload) {
														aiMessage.content = data.payload.content || '';
														if (data.payload.knowledge) {
															aiMessage.knowledge = data.payload.knowledge;
														}
													}
												} catch (parseError) {
													console.error('JSON解析失败：', parseError);
													console.log('问题数据：', jsonStr);
												}
											}
										}
									}

									// 如果没有有效的回复数据
									if (!lastValidData) {
										throw new Error('未收到有效的回复数据');
									}

								} catch (error) {
									console.error('处理响应数据失败：', error);
									throw error;
								}
							} else {
								throw new Error(`请求失败，状态码：${res.statusCode}`);
							}
						},
						fail: (err) => {
							console.error('请求失败：', err);
							throw new Error(err.errMsg);
						}
					});

				} catch (error) {
					console.error('请求失败：', error);
					const lastMessage = this.messages[this.messages.length - 1];
					if (lastMessage.type === 'ai') {
						lastMessage.content = '抱歉，服务出现了问题：' + error.message;
					}
					uni.showToast({
						title: '请求失败：' + error.message,
						icon: 'none',
						duration: 2000
					});
				}
			},

			// 测试连接
			async testConnection() {
				try {
					const testMessage = "你好";
					await this.sendToKnowledgeBot(testMessage);
				} catch (error) {
					console.error('测试连接失败：', error);
				}
			},

			// 语音识别完成后的处理
			async onSpeechResult(result) {
				if (result) {
					// 发送到知识库获取回答
					await this.sendToKnowledgeBot(result);
				}
			},

			// 初始化录音管理器
			initRecorder() {
				try {
					this.recorderManager = uni.getRecorderManager();
					this.innerAudioContext = uni.createInnerAudioContext();
					
					// 配置录音参数
					const recorderOptions = {
						duration: 60000,
						sampleRate: 16000,
						numberOfChannels: 1,
						encodeBitRate: 96000,
						format: 'mp3',
						frameSize: 50
					};
					
					// 监听录音开始事件
					this.recorderManager.onStart(() => {
						console.log('录音开始');
						this.isRecording = true;
					});
					
					// 监听录音结束事件
					this.recorderManager.onStop((res) => {
						console.log('录音结束', res);
						this.isRecording = false;
						
						// 显示用户录音内容
						this.messages.push({type: 'user', content: '用户说话内容...'});
						
						// 模拟AI回复
						setTimeout(() => {
							this.messages.push({type: 'ai', content: '这是一段AI固定回复的内容，后续可以替换成真实的AI回复。'});
							// 播放固定语音回复
							this.innerAudioContext.src = '/static/demo-reply.mp3';
							this.innerAudioContext.play();
						}, 1000);
					});
					
					// 监听录音错误事件
					this.recorderManager.onError((res) => {
						console.error('录音错误：', res);
						this.isRecording = false;
						uni.showToast({
							title: '录音失败，请检查录音权限',
							icon: 'none'
						});
					});
					
				} catch (e) {
					console.error('初始化录音管理器失败：', e);
					uni.showToast({
						title: '录音功能初始化失败',
						icon: 'none'
					});
				}
			},
			
			// 初始化语音识别
			initSpeechRecognition() {
				if (!this.recognition) return;
				
				// 设置语音识别参数
				this.recognition.continuous = false; // 是否持续识别
				this.recognition.interimResults = false; // 是否返回中间结果
				this.recognition.lang = 'zh-CN'; // 设置语言为中文
				
				// 监听识别结果
				this.recognition.onresult = async (event) => {
					const result = event.results[0][0].transcript;
					console.log('语音识别结果：', result);
					
					// 发送到知识库获取回答
					await this.sendToKnowledgeBot(result);
				};
				
				// 监听错误
				this.recognition.onerror = (event) => {
					console.error('语音识别错误：', event.error);
					uni.showToast({
						title: '语音识别失败',
						icon: 'none'
					});
				};
				
				// 监听识别结束
				this.recognition.onend = () => {
					console.log('语音识别结束');
					this.isRecording = false;
				};
			},
			
			async startRecord(e) {
				// #ifdef H5
				try {
					// 检查和请求麦克风权限
					if (!this.mediaStream) {
						const stream = await navigator.mediaDevices.getUserMedia({
							audio: {
								echoCancellation: true,
								noiseSuppression: true,
								sampleRate: 16000
							}
						});
						this.mediaStream = stream;
					}
					
					// 开始语音识别
					if (this.recognition) {
						console.log('开始语音识别');
						this.recognition.start();
						this.isRecording = true;
						
						uni.showToast({
							title: '开始录音',
							icon: 'none'
						});
					} else {
						throw new Error('语音识别不可用');
					}
					
				} catch (err) {
					console.error('语音识别失败：', err);
					uni.showModal({
						title: '语音识别失败',
						content: '请确保已授予麦克风权限且使用支持的浏览器',
						showCancel: false
					});
				}
				// #endif
				
				// #ifndef H5
				// 非H5环境使用uni API
				if (!this.recorderManager) {
					this.initRecorder();
				}
				
				try {
					console.log('开始录音');
					this.recorderManager.start({
						duration: 60000,
						sampleRate: 16000,
						numberOfChannels: 1,
						encodeBitRate: 96000,
						format: 'mp3',
						frameSize: 50
					});
				} catch (err) {
					console.error('录音失败：', err);
					uni.showToast({
						title: '录音失败',
						icon: 'none'
					});
				}
				// #endif
				
				// 添加震动反馈
				uni.vibrateShort({
					success: function () {
						console.log('震动成功');
					}
				});
			},
			
			async stopRecord(e) {
				// #ifdef H5
				if (this.recognition && this.isRecording) {
					console.log('停止语音识别');
					this.recognition.stop();
				}
				
				if (this.mediaStream) {
					this.mediaStream.getTracks().forEach(track => track.stop());
					this.mediaStream = null;
				}
				// #endif
				
				// #ifndef H5
				if (this.recorderManager && this.isRecording) {
					this.recorderManager.stop();
				}
				// #endif
				
				uni.showToast({
					title: '录音结束',
					icon: 'none'
				});
				
				// 添加震动反馈
				uni.vibrateShort({
					success: function () {
						console.log('震动成功');
					}
				});
			},

			// 在组件销毁时关闭所有SSE连接
			beforeDestroy() {
				if (this.eventSource) {
					this.eventSource.close();
				}
			}
		}
	}
</script>

<style>
	.content {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
	}

	.logo {
		height: 200rpx;
		width: 200rpx;
		margin: 200rpx auto 50rpx auto;
	}

	.text-area {
		display: flex;
		justify-content: center;
	}

	.title {
		font-size: 36rpx;
		color: #8f8f94;
	}

	.chat-container {
		width: 100%;
		height: 60vh;
		padding: 20rpx;
		box-sizing: border-box;
	}

	.message {
		max-width: 80%;
		padding: 20rpx;
		margin: 20rpx;
		border-radius: 10rpx;
		word-break: break-all;
	}

	.user {
		background-color: #007AFF;
		color: #fff;
		margin-left: auto;
	}

	.ai {
		background-color: #F1F1F1;
		color: #333;
		margin-right: auto;
	}

	.voice-btn-container {
		width: 100%;
		padding: 40rpx;
		box-sizing: border-box;
		position: fixed;
		bottom: 0;
	}

	.voice-btn {
		width: 80%;
		height: 80rpx;
		line-height: 80rpx;
		background-color: #007AFF;
		color: #fff;
		border-radius: 40rpx;
		transition: all 0.3s;
	}

	.voice-btn:active {
		background-color: #0056b3;
		transform: scale(0.95);
	}

	/* 语音波纹动效 */
	.wave-container {
		position: fixed;
		top: 50%;
		left: 50%;
		transform: translate(-50%, -50%);
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		background: rgba(0, 0, 0, 0.7);
		border-radius: 20rpx;
		padding: 40rpx;
		z-index: 999;
	}

	.wave-wrapper {
		display: flex;
		align-items: center;
		justify-content: center;
		height: 160rpx;
		margin-bottom: 20rpx;
	}

	.wave-item {
		width: 8rpx;
		height: 40rpx;
		margin: 0 6rpx;
		background-color: #fff;
		border-radius: 4rpx;
		animation: waveAnimation 0.5s ease infinite alternate;
	}

	.wave-item:nth-child(2) {
		animation-delay: 0.2s;
		height: 60rpx;
	}

	.wave-item:nth-child(3) {
		animation-delay: 0.3s;
		height: 80rpx;
	}

	.wave-item:nth-child(4) {
		animation-delay: 0.4s;
		height: 50rpx;
	}

	@keyframes waveAnimation {
		0% {
			transform: scaleY(0.5);
		}
		100% {
			transform: scaleY(1.2);
		}
	}

	.wave-text {
		color: #fff;
		font-size: 28rpx;
	}

	/* 按钮样式优化 */
	.voice-btn {
		width: 80%;
		height: 80rpx;
		line-height: 80rpx;
		background-color: #007AFF;
		color: #fff;
		border-radius: 40rpx;
		transition: all 0.3s;
		position: relative;
		overflow: hidden;
	}

	.voice-btn.recording {
		background-color: #0056b3;
		transform: scale(0.95);
	}

	.voice-btn:active {
		background-color: #0056b3;
		transform: scale(0.95);
	}

	/* 对话气泡优化 */
	.message {
		max-width: 80%;
		padding: 20rpx;
		margin: 20rpx;
		border-radius: 20rpx;
		word-break: break-all;
		position: relative;
		animation: messagePopIn 0.3s ease-out;
	}

	.user {
		background-color: #007AFF;
		color: #fff;
		margin-left: auto;
		border-bottom-right-radius: 4rpx;
	}

	.ai {
		background-color: #F1F1F1;
		color: #333;
		margin-right: auto;
		border-bottom-left-radius: 4rpx;
	}

	@keyframes messagePopIn {
		0% {
			opacity: 0;
			transform: scale(0.8);
		}
		100% {
			opacity: 1;
			transform: scale(1);
		}
	}

	/* 聊天容器优化 */
	.chat-container {
		width: 100%;
		height: calc(100vh - 280rpx);
		padding: 20rpx;
		box-sizing: border-box;
		background-color: #f8f8f8;
	}

	/* 按钮容器固定在底部 */
	.voice-btn-container {
		width: 100%;
		padding: 20rpx 40rpx;
		box-sizing: border-box;
		position: fixed;
		bottom: 0;
		left: 0;
		background-color: #fff;
		box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
	}

	/* 添加知识库引用样式 */
	.knowledge-source {
		font-size: 24rpx;
		color: #999;
		margin-top: 10rpx;
	}

	.source-text {
		background-color: #f5f5f5;
		padding: 4rpx 8rpx;
		border-radius: 4rpx;
	}

	/* 添加打字机效果的样式 */
	.message.ai {
		animation: fadeIn 0.3s ease-out;
	}

	.message.ai .content {
		display: inline-block;
		min-height: 1.2em;
	}

	@keyframes fadeIn {
		from {
			opacity: 0;
			transform: translateY(10px);
		}
		to {
			opacity: 1;
			transform: translateY(0);
		}
	}
</style>
